import os
import sys
import shutil
import codecs
import argparse

regx_map = {
   "anlogic": "unknown",
   "Anlogic": "Unknown",
   "ANLOGIC": "UNKNOWN",
}

_TEXT_BOMS = (
    codecs.BOM_UTF16_BE,
    codecs.BOM_UTF16_LE,
    codecs.BOM_UTF32_BE,
    codecs.BOM_UTF32_LE,
    codecs.BOM_UTF8,
)

DEMO_HPF = [
    '\t\tDEMO_HPF_MAP.put("SOC66080_AD201", EnvUtils.getIDERootPath() + "/data/hpf/SOC66080.hpf");\n',
    '\t\tDEMO_HPF_MAP.put("SOC66080_FUNC", EnvUtils.getIDERootPath() + "/data/hpf/SOC66080_FUNC.hpf");\n'
] 

def is_binary_file(file_path):
    with open(file_path, 'rb') as file:
        initial_bytes = file.read(8192)
        file.close()
        for bom in _TEXT_BOMS:
            if initial_bytes.startswith(bom):
                continue
            else:
                if b'\0' in initial_bytes:
                    return True
    return False

def replace_content(file_path, output_path):
    try:
        if is_binary_file(file_path):
            shutil.copy(file_path, output_path)
            return
        fp_read = open(file_path, "r", encoding='utf-8')
        content = fp_read.read()
        fp_read.close()
        for key, value in regx_map.items():
            content = content.replace(key, value)
        fp_write = open(output_path, "w", encoding='utf-8')
        fp_write.write(content)
        fp_write.close()
    except Exception as e:
        print(file_path)
        print(e)

def desensitization(input_dir, output_dir, chip_list):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    for entry in os.scandir(input_dir):
        tmp_name = entry.name
        for key, value in regx_map.items():
            tmp_name = tmp_name.replace(key, value)
        tmp_output = os.path.join(output_dir, tmp_name)
        if entry.is_dir():
            if entry.name == "target" or entry.name == "bin":
                continue
            desensitization(entry, tmp_output, chip_list)
        elif entry.is_file():
            if entry.name == ".polyglot..META-INF_MANIFEST.MF":
                continue
            if entry.name == "desensitization.py":
                shutil.copy(entry.path, tmp_output)
                continue

            if entry.path.find("com.anlogic.sdk.bsp/src/com/anlogic/sdk/bsp/Constants.java") != -1 or entry.path.find("com.anlogic.sdk.bsp\\src\\com\\anlogic\\sdk\\bsp\\Constants.java") != -1:
                fp_read = open(entry.path, "r", encoding='utf-8')
                lines = fp_read.readlines()
                fp_read.close()
                new_lines = []
                has_add_demo_hpf = False
                for item in lines:
                    if item.find("DEMO_HPF_MAP.put") != -1:
                        if not has_add_demo_hpf:
                            new_lines.extend(DEMO_HPF)
                            has_add_demo_hpf = True
                        continue
                    new_lines.append(item)
                fp_write = open(tmp_output, "w", encoding='utf-8')
                fp_write.writelines(new_lines)
                fp_write.close()
                replace_content(tmp_output, tmp_output)
                continue

            # process chip.properties
            if entry.name == "chip.properties":
                fp_read = open(entry.path, "r", encoding='utf-8')
                lines = fp_read.readlines()
                fp_read.close()
                for item in lines:
                    chip, value = item.split("=")
                    if chip in chip_list:
                        lines[lines.index(item)] = chip + "=" + "true" + "\n"
                    else:
                        lines[lines.index(item)] = chip + "=" + "false" + "\n"
                fp_write = open(tmp_output, "w", encoding='utf-8')
                fp_write.writelines(lines)
                fp_write.close()
                continue

            # process other files
            # print("Processing: ", entry.path)
            replace_content(entry.path, tmp_output)

def main(args):
    input_dir = args.i
    output_dir = args.o
    chip_list = args.chip

    print("Desensitization starting... ")
    print(input_dir, " ====> ", output_dir)
    desensitization(input_dir, output_dir, chip_list)
    print("Desensitization Done!")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Process Desensitization')
    parser.add_argument('-i', default='', type=str, help='Input Directory')
    parser.add_argument('-o', default='', type=str, help='Output directory')
    parser.add_argument('-chip', default=["soc66080"], nargs="+", help='Supported chip list')
    args = parser.parse_args()

    main(args)
